package com.label.Utils;

import com.label.Config.MyBatis.IdGenerator;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author linyh
 * @email 1503386669@qq.com
 * @date 2020/7/27 14:55
 */
@Component
public class WordUtil {

    private static Logger logger = LoggerFactory.getLogger(WordUtil.class);
    private Configuration configuration;
    private String encoding;
    private String exportPath = "/home/hadoop/attrfile/picture/";
//    private String exportPath = "C:\\Users\\75046\\Desktop\\";

    /**
     * 构造函数
     * 配置模板路径
     */
    public WordUtil() throws IOException {
        this.encoding = "UTF-8";
        configuration = new Configuration();
        configuration.setDefaultEncoding(encoding);
        configuration.setClassForTemplateLoading(this.getClass(), "/static");
    }

    /**
     * 获取模板
     *
     * @param name
     * @return
     * @throws Exception
     */
    public Template getTemplate(String name) throws Exception {
        return configuration.getTemplate(name);
    }

    /**
     * 导出word文档到指定目录
     *
     * @param tplName
     * @param data
     * @throws Exception
     */
    public String exportDocFile(String tplName, Map<String, Object> data) throws Exception {
        //如果目录不存在，则创建目录
        File exportDirs = new File(exportPath);
        if (!exportDirs.exists()) {
            exportDirs.mkdirs();
        }
        String fileName = IdGenerator.uuid()+ ".pdf";
        Writer out = new StringWriter();
        try {
            getTemplate(tplName).process(data, out);
            Word2PdfAsposeUtil.doc2pdf(new ByteArrayInputStream(out.toString().getBytes()),exportPath+fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileName;
    }

    /**
     * 导出word文档到客户端
     *
     * @param response
     * @param tplName
     * @param data
     * @throws Exception
     */
    public void exportDoc(HttpServletResponse response, String tplName, Map<String, Object> data) throws Exception {
        String filename = IdGenerator.uuid();

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));

        File outFile = new File(exportPath + filename + ".doc");//输出路径
        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), StandardCharsets.UTF_8));
            getTemplate(tplName).process(data, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null)
                    out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        outFile = new File(exportPath + filename + ".doc");
        FileInputStream fis = new FileInputStream(outFile);
        OutputStream os = response.getOutputStream();
        // 常规操作
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        fis.close();
        os.close();
        os.flush();
    }

}
